<?php
require_once("config.php");

//header("content-type: text/calendar");

function MySQLDate2VCalDate($date)
{
	return substr($date, 0, 4).substr($date, 5, 2).substr($date, 8, 2);
}

function MySQLTime2VCalTime($time)
{
	$heure=intVal(substr($time, 0 ,2));
	return str_pad($heure, 2, "0", STR_PAD_LEFT).substr($time, 3, 2)."00";
}

function add10ToTime($time)
{
	$heure=intVal(substr($time, 0 ,2));
	$minute=intVal(substr($time, 3, 2));
	$seconde=intVal(substr($time, 6, 2));

	$minute+=10;
	if($minute >= 60)
	{
		$minute-=60;
		$heure++;
	}

	if($heure == 24) $heure=0;
	return str_pad($heure, 2, "0", STR_PAD_LEFT).":".str_pad($minute, 2, "0", STR_PAD_LEFT).":".str_pad($seconde, 2, "0", STR_PAD_LEFT);
}

$rappel=false;
if(isset($_GET["rappel"]))
{
	$rappel=($_GET["rappel"] == 1);
}

echo "BEGIN:VCALENDAR\n";
echo "VERSION:2.0\n";
echo "PRODID:-//amanda/NONSGML Amanda Calendar V1.1//FR\n";

$db=mysql_connect($config["serveur"], $config["user"], $config["passWord"]);
mysql_select_db($config["dataBase"], $db);

$sql="SELECT code, p.nom, dateAction, heureAction, action, a.commentaires ";
$sql.="FROM actionsProspect as a INNER JOIN prospect as p ON prospect=code ";
$sql.="WHERE qui = \"".$_GET["qui"]."\" and heureAction != \"00:00:00\" and action=\"\" ";
$sql.="UNION ";
$sql.="SELECT code, c.nom, dateAction, heureAction, action, a.commentaires ";
$sql.="FROM actionsClient as a INNER JOIN client as c ON client=code ";
$sql.="WHERE qui = \"".$_GET["qui"]."\" and heureAction != \"00:00:00\" and action=\"\"";

$result=mysql_query($sql, $db);
while($row=mysql_fetch_array($result))
{
	echo "BEGIN:VEVENT\n";
	echo "DTSTART:".MySQLDate2VCalDate($row["dateAction"])."T".MySQLTime2VCalTime($row["heureAction"])."\n";
	echo "DTEND:".MySQLDate2VCalDate($row["dateAction"])."T".MySQLTime2VCalTime(add10ToTime($row["heureAction"]))."\n";
	echo "SUMMARY:".$row["code"].": ".utf8_encode($row["nom"])."\n";
	echo "DESCRIPTION:".str_replace("\n", "\\n", utf8_encode($row["commentaires"]))."\n";
	if($rappel)
	{
		echo "BEGIN:VALARM\n";
		echo "TRIGGER;VALUE=DURATION:-PT5M\n";
		echo "ACTION:DISPLAY\n";
		echo "END:VALARM\n";
	}
	echo "END:VEVENT\n";
}

mysql_close($db);

echo "END:VCALENDAR\n";

?>
